<template>
  <CDialog
    :visible="visible"
    v-loading="loading"
    :title="title"
    type="add"
    width="630px"
    @submit="handleSubmit"
    @cancel="handleCancel"
    @outerOpen="outerOpen"
  >
    <div v-if="type === 'update'">
      {{
        this.row.status === 'ON_SALE'
          ? '提示：该时长卡停止发售，已购买该时长卡用户将继续使用。'
          : '确定上架该通用时长卡？'
      }}
    </div>
    <div v-else-if="type === 'batch'">
      <LoadFile v-model="batchData" ref="loadFile" />
    </div>
    <div v-else-if="type === 'present'">
      <i-form ref="form" :items="formItems" :model="form" :rules="rules">
      </i-form>
    </div>
    <div v-else-if="type === 'delete'">确定要删除该通用时长卡?</div>
    <PackageDelWarnDlg
      v-if="warnDlgVisible"
      :visible.sync="warnDlgVisible"
      type="timeCard"
      :station-names="stationNames"
      @closeOuter="handleCancel"
    >
    </PackageDelWarnDlg>
  </CDialog>
</template>
<script>
import CDialog from '@/components/CDialog'
import LoadFile from '@/components/LoadFile'
import PackageDelWarnDlg from './PackageDelWarnDlg'
import {
  updateMerchantTimecardStatus,
  persentMerchantTimecard,
  deleteMerchantTimeCard,
} from '@/api/mySelf'
import formValidate from '@/utils/validate'
export default {
  name: 'AgentFunctionDialog',
  components: { CDialog, LoadFile, PackageDelWarnDlg },
  data() {
    return {
      warnDlgVisible: false,
      batchData: [],
      loading: false,
      formItems: [
        {
          label: '用户手机号:',
          type: 'text',
          value: 'mobile',
          required: true,
        },
        {
          label: '确认手机号',
          type: 'text',
          value: 'userMobile',
          required: true,
        },
      ],
      form: {},
      rules: {
        userMobile: [
          {
            validator: (rules, value, callback) => {
              if (this.form.mobile !== this.form.userMobile) {
                callback(new Error('电话号码不一致'))
              } else {
                callback()
              }
            },
          },
          {
            validator: formValidate('validateMobile'),
          },
        ],
        mobile: [
          {
            validator: formValidate('validateMobile'),
          },
        ],
      },
    }
  },
  props: {
    visible: {
      required: true,
      type: Boolean,
    },
    type: {
      required: true,
      type: String,
    },
    row: {
      type: Object,
    },
    title: {
      required: true,
      type: String,
    },
  },
  methods: {
    handleUpdate() {
      // if (this.loading) return

      // this.loading = true
      updateMerchantTimecardStatus({
        id: this.row.id,
        status: this.row.status === 'ON_SALE' ? 'OFFLINE' : 'ON_SALE',
      })
        .then(() => {
          this.$message({
            type: 'success',
            message: '操作成功',
            showClose: true,
          })

          this.$emit('update:visible', false)
          this.$emit('refresh')
        })
        .catch((err) => {
          if (err.code === 40030) {
            this.warnDlgVisible = true
            this.stationNames = err.data.join(',')
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handlePresent() {
      if (this.loading) return
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }

        let params = {
          initialTime: this.row.initialTime,
          mobile: this.form.userMobile,
          powerCharging: this.row.powerCharging,
          // stationIds: this.row.stationIds || '',
          timeCardExpire: this.row.periodOfValidity,
        }

        if (this.row.stationIds && this.row.stationIds !== '') {
          params.stationIds = this.row.stationIds
        }

        this.loading = true
        persentMerchantTimecard(params)
          .then(() => {
            this.$message({
              type: 'success',
              message: '操作成功',
              showClose: true,
            })

            this.$emit('update:visible', false)
            this.$emit('refresh')
          })
          .catch((err) => {
            console.log(err)
          })
          .finally(() => {})
      })
    },
    handleBatchPresent() {
      let phoneArr = []
      let phoneStr = ''
      let phoneReg = /^1[0-9]{10}$/
      if (this.batchData.length <= 0) {
        this.$message({
          showClose: true,
          message: '数据导入失败,请上传正确的数据表格',
          type: 'warning',
        })
        this.$refs.loadFile.onRemove()
        return
      }
      this.batchData.some((item) => {
        if (item['用户手机号']) {
          let phone = item['用户手机号']
            .toString()
            .replace(/(^\s*)|(\s*$)/g, '')
          phoneArr.push(phone)
          if (!phoneReg.test(phone)) {
            this.$message({
              showClose: true,
              message: `电话:${phone}, 格式错误请修正！`,
              type: 'warning',
            })
            phoneArr = []
            return true
          }
        }
      })

      if (phoneArr.length > 0) {
        phoneStr = phoneArr.join(',')
      } else {
        this.$message({
          message: '数据导入失败',
          type: 'error',
          offset: 60,
        })
        this.batchData = []
        this.$refs.loadFile.onRemove()
        return
      }

      let params = {
        initialTime: this.row.initialTime,
        mobile: phoneStr,
        powerCharging: this.row.powerCharging,
        timeCardExpire: this.row.periodOfValidity,
      }

      if (this.row.stationIds && this.row.stationIds !== '') {
        params.stationIds = this.row.stationIds
      }

      persentMerchantTimecard(params)
        .then(() => {
          this.$message({
            type: 'success',
            message: '操作成功',
            showClose: true,
          })

          this.$emit('update:visible', false)
          this.$emit('refresh')
        })
        .catch((err) => {
          this.batchData = []
          this.$refs.loadFile.onRemove()
          console.log(err)
        })
    },
    handleDelete() {
      deleteMerchantTimeCard({ id: this.row.id }).then(() => {
        this.$message({
          type: 'success',
          message: '操作成功',
          showClose: true,
        })

        this.$emit('update:visible', false)
        this.$emit('refresh')
      })
    },
    handleSubmit() {
      if (this.type === 'update') {
        this.handleUpdate()
        return
      } else if (this.type === 'batch') {
        this.handleBatchPresent()
        return
      } else if (this.type === 'present') {
        this.handlePresent()
        return
      } else if (this.type === 'delete') {
        this.handleDelete()
      }
      // this.$emit('update:visible', false)
    },
    handleCancel() {
      this.$emit('update:visible', false)
    },
    outerOpen() {
      this.$nextTick(() => {
        if (this.$refs.form) this.$refs.form.clearValidate()
      })

      this.form = {}
    },
  },
}
</script>
